//
//  YWModifyPatrolLineTableViewController.m
//  maintain
//
//  Created by Kyo on 16/10/12.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWModifyPatrolLineTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "YWLoginTool.h"

#import "MBProgressHUD.h"
#import "YWTextFieldCell.h"
#import "YWWriteNoteCell.h"
#import "YWPatrolLocationTableViewCell.h"
#import "YWWriteIntervalTimeTableViewCell.h"

#import "YWLocation.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"

//#import "YWSelectBuildingTableViewController.h"
#import "YWSelectPatrolLocationTableViewController.h"
#import "YWSelectWeekTableViewController.h"
#import "YWSelectTimeUnitTableViewController.h"

#import "YWKeepWatchMissionManager.h"

@interface YWModifyPatrolLineTableViewController ()<YWTextFieldCellDelegate,YWWriteNoteCellDelegate,YWSelectWeekTableViewControllerDelegate,YWSelectPatrolLocationTableVCDelegate,YWWriteIntervalTimeTableViewCellDelegate,YWSelectTimeUnitTableVCDelegate>{
    YWBuilding *currentBuilding;
    NSString *patrolLineName;
    NSString *patrolIntervalTime;
    NSString *currentTimeUnit;
    NSString *linenNote;
    
    NSString *weekString;
}
@property (nonatomic, strong) NSMutableArray *selectLocationArray;
@property (nonatomic, strong) NSMutableArray *selectWeekArray;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWModifyPatrolLineTableViewController

- (instancetype)init{
    return [super  initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"modifyKeepWatchLine", nil);
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickCancelBarButtonEvent:)];
    
    [self setupData];
    [self initTableView];
}

- (void)setupData{
    patrolLineName = self.patrolLine.patrolLineName;
    linenNote = self.patrolLine.note;
    NSInteger minutes = self.patrolLine.intervalMinute;
    
    if (minutes<60) {
        currentTimeUnit = NSLocalizedString(@"minute", nil);
        patrolIntervalTime = [@(minutes) stringValue];
    }else if (minutes>=60 && minutes<60*24){
        currentTimeUnit = NSLocalizedString(@"hour", nil);
        patrolIntervalTime = [@(minutes/60) stringValue];
    }
    YWPatrolLineLocationRel *locationRel = [self.patrolLine.locationRels count]?self.patrolLine.locationRels[0] : nil;
    YWBuilding *building = [[YWBuildingManager shareManager] buildingWithLocationId:locationRel.locationId];
    currentBuilding = building;
    
    [self.patrolLine.locationRels enumerateObjectsUsingBlock:^(YWPatrolLineLocationRel*  _Nonnull locationRel, NSUInteger idx, BOOL * _Nonnull stop) {
        YWLocation *location = [[YWBuildingManager shareManager] locationWithId:locationRel.locationId];
        if (location) {
            location.note = locationRel.note;
            [self.selectLocationArray addObject:location];
        }
    }];
    
    NSString *weekStr = @"";
    for (YWPatrolLineWeekRel *weekRel in self.patrolLine.weekRels) {
        NSString *week = [YWCommonTool weekDayString:weekRel.week];
        if (week) {
            weekStr = [weekStr stringByAppendingString:week];
            weekStr = [weekStr stringByAppendingString:@","];
            [self.selectWeekArray addObject:week];
        }
    }
    weekStr = weekStr.length>=1?[weekStr substringToIndex:weekStr.length-1]:NSLocalizedString(@"none", nil);
    weekString = weekStr;
}

- (void)initTableView{
    [self.tableView registerClass:[YWTextFieldCell class] forCellReuseIdentifier:YWTextFieldCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWPatrolLocationTableViewCell class] forCellReuseIdentifier:YWPatrolLocationTableViewCellIdentifier];
    [self.tableView registerClass:[YWWriteIntervalTimeTableViewCell class] forCellReuseIdentifier:YWWriteIntervalTimeTableViewCellIdentifier];
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 5){
        return 90;
    }else if (indexPath.section == 2){
        return indexPath.row==0 ? 44 : 70;
    }
    else{
        return 44;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section==2? self.selectLocationArray.count + 1 : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"YWSelecrPatrolLocationReuseCellIdentifier";
    UITableViewCell *locationCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (locationCell == nil) {
        locationCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        locationCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        locationCell.textLabel.font = kContentFont;
    }
    
    if (indexPath.section == 1) {
        YWTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTextFieldCellIdentifier];
        cell.delegate = self;
        cell.textFieldContent = patrolLineName;
        cell.textFieldPlaceholder = NSLocalizedString(@"writeKeepWatchLineName", nil);//@"请填写巡更路线名称";
        return cell;
    }else if (indexPath.section == 2){
        if (indexPath.row==0) {
            locationCell.textLabel.text = NSLocalizedString(@"selectKeepWatchLocation", nil);//@"请选择巡更位置";
            return locationCell;
        }else{
            YWPatrolLocationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:YWPatrolLocationTableViewCellIdentifier];
            YWLocation *location = self.selectLocationArray[indexPath.row-1];
            cell.location = location;
            return cell;
        }
        
    }else if (indexPath.section == 0|| indexPath.section==4){
        if (indexPath.section==0) {
            locationCell.textLabel.text = currentBuilding ? currentBuilding.buildingName : NSLocalizedString(@"none", nil);
            locationCell.accessoryType = UITableViewCellAccessoryNone;
            return locationCell;
        }else {
            locationCell.textLabel.text = weekString.length>0 ? weekString : NSLocalizedString(@"selectKeepwatchDay", nil);
            return locationCell;
        }
    }else if (indexPath.section == 3){
        YWWriteIntervalTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteIntervalTimeTableViewCellIdentifier];
        cell.delegate = self;
        cell.textFieldPlaceholder = NSLocalizedString(@"writeKeepWatchIntervalTime", nil);
        cell.intervalTime = patrolIntervalTime;
        cell.currentTimeUnit = currentTimeUnit;
        return cell;
        
    }else{
        YWWriteNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.inputTextMaxCount = 300;
        cell.delegate = self;
        cell.textViewContent = linenNote;
        return cell;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 && [self.selectLocationArray count]>0 && indexPath.row>0) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2 && [self.selectLocationArray count]>0 && indexPath.row>0) {
        [self.selectLocationArray removeObjectAtIndex:indexPath.row-1];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        //        if (self.selectLocationArray.count==0) {
        //            [tableView reloadData];
        //        }else{
        //            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        //        }
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWSelecrPatrolLocationForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section==0) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        NSString *title = buildingShowName.length?buildingShowName:NSLocalizedString(@"building", nil);
        return title;
    }else if (section == 1) {
        return NSLocalizedString(@"lineName", nil);//@"路线名称";
    }else if (section==2){
        return NSLocalizedString(@"lineLocation", nil);//@"巡更位置";
    }else if (section==3){
        return NSLocalizedString(@"keepWatchInterval", nil);//@"巡更间隔";
    }else if (section==4){
        return NSLocalizedString(@"keepWatchDay", nil);//@"巡更日";
    }else if (section==5){
        return NSLocalizedString(@"note", nil);//@"备注";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }else if (indexPath.section == 2 && indexPath.row==0) {
        YWSelectPatrolLocationTableViewController *selectLocationVC = [[YWSelectPatrolLocationTableViewController alloc] init];
        selectLocationVC.delegate = self;
        selectLocationVC.buildingId = currentBuilding.buildingId;
        selectLocationVC.ownLocationArray = self.selectLocationArray;
        [self.navigationController pushViewController:selectLocationVC animated:YES];
    }else if (indexPath.section == 4){
        YWSelectWeekTableViewController *selectWeekVC = [[YWSelectWeekTableViewController alloc] init];
        selectWeekVC.title = NSLocalizedString(@"selectKeepwatchDay", nil);
        selectWeekVC.delegate = self;
        selectWeekVC.ownWeekArray = self.selectWeekArray;
        [self.navigationController pushViewController:selectWeekVC animated:YES];
    }
}

#pragma mark - YWSelectPatrolLocationTableVCDelegate
- (void)selectPatrolLocations:(NSArray *)locationArray{
    [self.selectLocationArray removeAllObjects];
    [self.selectLocationArray addObjectsFromArray:locationArray];
    [self.patrolLine.locationRels enumerateObjectsUsingBlock:^(YWPatrolLineLocationRel*  _Nonnull locationRel, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", locationRel.locationId];
        NSArray *array = [self.selectLocationArray filteredArrayUsingPredicate:searchPredicate];
        if (array.count==1) {
            YWLocation *location = array[0];
            location.note = locationRel.note;;
        }
    }];
    [self.tableView reloadData];
}
#pragma mark - YWSelectWeekTableViewControllerDelegate
- (void)selectWeeks:(NSArray *)weekArray{
    [self.selectWeekArray removeAllObjects];
    [self.selectWeekArray addObjectsFromArray:weekArray];
    NSMutableString *weekStr = [[NSMutableString alloc] init];
    [self.selectWeekArray enumerateObjectsUsingBlock:^(NSString*  _Nonnull week, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx!=0) {
            [weekStr appendString:@","];
        }
        if (week.length) {
            [weekStr appendString:week];
        }
    }];
    weekString = [NSString stringWithFormat:@"%@",weekStr];
    [self.tableView reloadData];
}

#pragma mark - YWTextFieldCellDelegate
- (void)passTextFieldContent:(NSString *)content cell:(UITableViewCell *)cell{
    NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];
    if (indexpath.section==1) {
        patrolLineName = content;
    }
}
#pragma mark - YWWriteIntervalTimeTableViewCellDelegate
- (void)passIntervalTime:(NSString *)intervalTime cell:(UITableViewCell *)cell{
    patrolIntervalTime = intervalTime;
}

- (void)clickUnitButtonEvent:(UITableViewCell *)cell{
    YWSelectTimeUnitTableViewController *selectUnitVC = [[YWSelectTimeUnitTableViewController alloc] init];
    selectUnitVC.delegate = self;
    selectUnitVC.currentUnit = currentTimeUnit;
    selectUnitVC.unitArray = @[NSLocalizedString(@"minute", nil),NSLocalizedString(@"hour", nil)];
    [self.navigationController pushViewController:selectUnitVC animated:YES];
}

#pragma mark - YWSelectTimeUnitTableVCDelegate
- (void)popSelectTimeUnit:(NSString *)unit{
    currentTimeUnit = unit;
    [self.tableView reloadData];
}

#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString *)note{
    linenNote = note;
}

- (NSMutableArray *)selectLocationArray{
    if (!_selectLocationArray) {
        _selectLocationArray = [NSMutableArray array];
    }
    return _selectLocationArray;
}

- (NSMutableArray *)selectWeekArray{
    if (!_selectWeekArray) {
        _selectWeekArray = [NSMutableArray array];
    }
    return _selectWeekArray;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:NSLocalizedString(@"commit", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickSenderButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextSubmitTask, nil);//@"提交中";
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)clickSenderButtonEvent:(id)sender{
    if (patrolLineName.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"writeKeepWatchLineName", nil)];
        return;
    }
    if (patrolLineName.length>50) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"lineNameLengthNoMoreThan50", nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:patrolLineName]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (linenNote.length>100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:linenNote]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (self.selectLocationArray.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"selectKeepWatchLocation", nil)];
        return;
    }
    if (self.selectWeekArray.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"selectKeepwatchDay", nil)];
        return;
    }
    if ([patrolIntervalTime integerValue] == 0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"keepWatchIntervalTimeCannotBeZero", nil)];
        return;
    }if ([currentTimeUnit isEqualToString:NSLocalizedString(@"minute", nil)] && [patrolIntervalTime integerValue] >= 60) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"selectHourUnitIfIntervalTimeMoreThan60Minutes", nil)];
        return;
    }if ([currentTimeUnit isEqualToString:NSLocalizedString(@"hour", nil)] && [patrolIntervalTime integerValue] >= 24){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"intervalTimeCannotBeOrMoreThan24Hour", nil)];
        return;
    }
    __block BOOL containEmoji = NO;
    [self.selectLocationArray enumerateObjectsUsingBlock:^(YWLocation*  _Nonnull location, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([YWCommonTool isContainsEmoji:location.note]) {
            containEmoji = YES;
            *stop = YES;
        }
    }];
    if (containEmoji) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    //点击提交
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makSureToCommit", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [self modifyPatrolLine];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)modifyPatrolLine{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@(_patrolLine.patrolLineId) forKey:@"patrolLineId"];
    [params setValue:patrolLineName forKey:@"patrolLineName"];
    NSInteger intervalMinute = [currentTimeUnit isEqualToString:NSLocalizedString(@"hour", nil)] ? [patrolIntervalTime integerValue] *60 : [patrolIntervalTime integerValue];
    [params setValue:@(intervalMinute) forKey:@"intervalMinute"];
    [params setValue:linenNote?:@"" forKey:@"note"];
    [self.selectLocationArray enumerateObjectsUsingBlock:^(YWLocation*  _Nonnull location, NSUInteger idx, BOOL * _Nonnull stop) {
        [params setValue:@(location.locationId) forKey:[NSString stringWithFormat:@"locationRels[%lu].location.locationId",(unsigned long)idx]];
        [params setValue:@(idx+1) forKey:[NSString stringWithFormat:@"locationRels[%lu].sort",(unsigned long)idx]];
        [params setValue:location.note?:@"" forKey:[NSString stringWithFormat:@"locationRels[%lu].note",(unsigned long)idx]];
    }];
    [self.selectWeekArray enumerateObjectsUsingBlock:^(NSString*  _Nonnull week, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger weekInt = [YWCommonTool weekOfString:week];
        [params setValue:@(weekInt) forKey:[NSString stringWithFormat:@"weekRels[%lu].week",(unsigned long)idx]];
    }];
    [[YWKeepWatchMissionManager shareManager] modifyKeepWatchLine:params completeBlock:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshModifyPatrolLineNotification object:nil];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"modifyKeepWatchLineSucceed", nil)];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (void)clickCancelBarButtonEvent:(id)sender{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"quitEditing", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
